package communication;

import java.util.ArrayList;

import control.Supervisorio;
import entities.Variable;

public class MainCOMM {
	// será ativada ao ser iniciada a supervisao
	// receber as variaveis
	// conectar na serial
	// autorizar envio
	// receber
	// modificar valores das variáveis

	// comunicacao
	private boolean busyFlag = false;
	private boolean free = true;

	private boolean isThreadAlive;

	private ModbusModem modem;

	// variaveis
	private ArrayList<Variable> variables;
	private char[] varAdd;
	private char[] varCAdd;

	private Supervisorio supervisorio;

	public void MainCOMM() {
		supervisorio = Supervisorio.getInstance();
	}

	public void stopCommunication() {
		isThreadAlive = false;
		modem.Close();
	}

	public boolean initiateCommunication(ArrayList<Variable> v) {
		variables = v;
		varAdd = new char[variables.size()];
		varCAdd = new char[variables.size()];
		getAddresses();

		isThreadAlive = true;

		modem = new ModbusModem();
		if (!modem.Connect(varAdd, varCAdd))
			return false;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

		Thread t = new Thread(new Runnable() {
			public void run() {
				while (isThreadAlive) {
					char[] x;
					x = modem.requestData();

					while (!free) {
					}

					busyFlag = true;
					if (x != null) {
						if (x.length == variables.size()) {
							for (int i = 0; i < variables.size(); i++) {
								variables.get(i).setValue(x[i]);

							}
						}

						busyFlag = false;

					}
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		// disparar a Thread
		t.start();

		// modem.requestData();
		// modem.Close();
		return false;

	}

	public void getAddresses() {
		for (int i = 0; i < variables.size(); i++) {
			varAdd[i] = variables.get(i).getAddress();
			varCAdd[i] = variables.get(i).getControllerAddress();
		}
	}

	public boolean isBusyFlag() {
		return busyFlag;
	}

	public void setBusyFlag(boolean busyFlag) {
		this.busyFlag = busyFlag;
	}

	public boolean isFree() {
		return free;
	}

	public void setFree(boolean free) {
		this.free = free;
	}

}
